package learn;

public class SparseArray {
    public static void main(String[] args) {
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[5][6] = 2;
        System.out.println("原始数组为");
        for (int[] row : chessArr1) {
            for (int item : row) {
                System.out.print("  " + item);
            }
            System.out.println();
        }
        //二维数组转换为稀疏数组
        /*
         * 1 遍历二维数组 得到非零数据的个数
         */
        int sum = 0;
        for (int[] row : chessArr1) {
            for (int item : row) {
                if (item != 0) {
                    sum++;
                }
            }
        }
        System.out.println("非零数据的个数: " + sum);

        //创建稀疏数组
        int[][] sparseArray = new int[sum + 1][3];
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;

        //非0数据的编号
        int count = 1;
        for (int i = 0; i < chessArr1.length; i++) {
            for (int j = 0; j < chessArr1[i].length; j++) {
                if (chessArr1[i][j] != 0) {
                    sparseArray[count][0] = i;
                    sparseArray[count][1] = j;
                    sparseArray[count][2] = chessArr1[i][j];
                    count++;
                }
            }
        }
        System.out.println("稀疏数组为");
        for (int[] row : sparseArray) {
            for (int item : row) {
                System.out.print("  " + item);
            }
            System.out.println();
        }

        //恢复二维数组
        /*
         *1 读取稀疏数组
         */
        int[][] chessArray2 = new int[sparseArray[0][0]][sparseArray[0][1]];
        for (int i = 1; i < sparseArray.length; i++) {
            chessArray2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        System.out.println("复原后的数组为");
        for (int[] row : chessArray2) {
            for (int item : row) {
                System.out.print("  " + item);
            }
            System.out.println();
        }
    }
}
